package org.xiaojl.sys.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.sys.entity.SysResource;
import org.xiaojl.sys.service.SysResourceService;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysResource")
public class SysResourceController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysResourceController.class);
	private static final String basePagePath = "sys/resource/";
	@Autowired
	private SysResourceService sysResourceService;
	
	@RequestMapping("/list")
	public String List(Model model){
		String treeData = sysResourceService.selectAllResourceTree();
		log.debug("获取到资源页面的treelist："+treeData);
		model.addAttribute("tree", treeData);
		return basePagePath+"list";
	}
	
	/**
	 * 进入新菜单添加页面.
	 */
//	@RequiresPermissions("pms:menu:add")
	@RequestMapping("/addUI")
	public String addUI(HttpServletRequest req, SysResource resource, Model model, Long pid) {
		if (null != pid) {
			SysResource parentResource = sysResourceService.selectById(pid);
			resource.setParentResource(parentResource);
			model.addAttribute("resource",resource);
		}
		return basePagePath+"add";
	}
	
	/**
	 * 保存新增菜单.
	 */
//	@RequiresPermissions("pms:menu:add")
	@RequestMapping("/add")
	public String addPmsMenu(HttpServletRequest req, SysResource resource, Model model, DwzAjax dwz) {
		try {
			String name = resource.getName();
			Wrapper<SysResource> wrapper = new EntityWrapper<SysResource>();
			wrapper.eq("name", name);
			wrapper.eq("type", "0");
			List<SysResource> list = sysResourceService.selectList(wrapper);
			if (list.size() > 0) {
				return operateError("菜单名称不能重复", model);
			}
			resource.setCreateBy(getSessionUser().getSysUser().getId());
			resource.setIsLeaf(0);//是叶子吗：0-是，1-不是
			if (null != resource.getParentResource().getId()) {
				resource.setLevel(resource.getParentResource().getLevel()+1);
				resource.setPid(resource.getParentResource().getId());
			}else{
				resource.setLevel(1);
				resource.setPid(0L);
			}
			sysResourceService.insert(resource);
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("新增资源出现异常:", e);
			return operateError("新增资源出错", model);
		}
		return operateSuccess(model, dwz);
	}
	
	/**
	 * 进入菜单修改页面.
	 */
//	@RequiresPermissions("pms:menu:edit")
	@RequestMapping("/editUI")
	public String editUI(HttpServletRequest req, Long id, Model model) {
		if (null != id) {
			SysResource resource = sysResourceService.selectById(id);
			//
			long pid = resource.getPid();
			if(pid!=0){
				SysResource parent = sysResourceService.selectById(pid);
				resource.setParentResource(parent);
			}
			
			model.addAttribute("resource",resource);
		}
		return basePagePath+"edit";
	}
	
	/**
	 * 保存要修改的菜单.
	 * 
	 * @return
	 */
//	@RequiresPermissions("pms:menu:edit")
	@RequestMapping("/edit")
	public String editPmsMenu(HttpServletRequest req, SysResource resource, Model model, DwzAjax dwz) {
		try {
			SysResource parent = resource.getParentResource();
			if (null == parent) {
				parent = new SysResource();
				parent.setId(0L);
			}
			resource.setPid(parent.getId());
			sysResourceService.updateById(resource);
			// 记录系统操作日志
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("更新资源信息出现异常:", e);
			return operateError("更新资源信息出错", model);
		}
	}
	
	/**
	 * 删除菜单.
	 */
//	@RequiresPermissions("pms:menu:delete")
	@RequestMapping("/delete")
	public String delPmsMenu(HttpServletRequest req, Long id, Model model, DwzAjax dwz) {
		try {
			if (id == null || id == 0) {
				return operateError("无法获取要删除的数据", model);
			}
			SysResource menu = sysResourceService.selectById(id);
			if (menu == null) {
				return operateError("无法获取要删除的数据", model);
			}
			Long parentId = menu.getParentResource().getId(); // 获取父菜单ID

			// 先判断此菜单下是否有子菜单
			Wrapper<SysResource> wrapper = new EntityWrapper<SysResource>();
			wrapper.eq("pid", id);
			List<SysResource> childMenuList = sysResourceService.selectList(wrapper);
			if (childMenuList != null && !childMenuList.isEmpty()) {
				return operateError("此菜单下关联有【" + childMenuList.size() + "】个子菜单，不能支接删除!", model);
			}

			// 删除掉菜单
			sysResourceService.deleteById(id);

			// 删除菜单后，要判断其父菜单是否还有子菜单，如果没有子菜单了就要将其父菜单设为叶子节点
			wrapper = new EntityWrapper<SysResource>();
			wrapper.eq("pid", parentId);
			List<SysResource> childList = sysResourceService.selectList(wrapper);
			if (childList == null || childList.isEmpty()) {
				// 此时要将父菜单设为叶子
				SysResource parent = sysResourceService.selectById(parentId);
				parent.setIsLeaf(0);
				sysResourceService.updateById(parent);
			}
			// 记录系统操作日志
			return operateSuccess(model, dwz);
		} catch (Exception e) {
			// 记录系统操作日志
			log.error("删除菜单出错:", e);
			return operateError("删除菜单出错", model);
		}
	}
}
